package io.nutz.nutzsite.common.utils;

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;

import org.apache.commons.codec.binary.Base64;

public class DESCryption {
	   // DES加密的私钥，必须是8位长的字符串
	    private static final byte[] DESkey = { 6, 120, 10, 5, 7, 50, 8, 25, 6, 120, 10, 5, 7, 50, 8, 25 };// 设置密钥、
	    private static final byte[] DESIV = { 0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xAF};// 设置向量
	    private static final String PASSWORD_CRYPT_KEY = "huhs;,t.".substring(0,8);  

	    private static AlgorithmParameterSpec iv = null;// 加密算法的参数接口，IvParameterSpec是它的一个实现
	    private static Key key = null;

	    public DESCryption() throws Exception {//byte[] DESkey,byte[] DESIV
	        DESKeySpec keySpec = new DESKeySpec(DESkey);// 设置密钥参数
	        iv = new IvParameterSpec(DESIV);// 设置向量
	        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
	        key = keyFactory.generateSecret(keySpec);// 得到密钥对象

	    }
	//加密方法
	    public String encode(String data) throws Exception {
	        Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
	        enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式，给出密钥和向量
	        byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
	        //BASE64Encoder base64Encoder = new BASE64Encoder();//太旧，版本放弃
	        return Base64.encodeBase64String(pasByte);
	    }
	//解密方法
	    public String decode(String data) throws Exception {
	        Cipher deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
	        deCipher.init(Cipher.DECRYPT_MODE, key, iv);
	        //BASE64Decoder base64Decoder = new BASE64Decoder();
	        byte[] pasByte = deCipher.doFinal(Base64.decodeBase64(data));
	        return new String(pasByte, "UTF-8");
	    }
	  //解密数据 
	public static String decrypt(String message) {
		try {
			String key = PASSWORD_CRYPT_KEY;
			byte[] bytesrc = convertHexString(message);
			Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
			DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
			IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
			cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
			byte[] retByte = cipher.doFinal(bytesrc);
			return new String( retByte ,"utf-8" );
		} catch (Exception e) {
			return "error";
		}
	}

	public static byte[] encrypt(String message, String key) throws Exception {
		
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

		DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));

		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
		IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
		cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

		return cipher.doFinal(message.getBytes("UTF-8"));
	}

	public static String encrypt(String value) {
		String result = "";
		try {
			//value = java.net.URLEncoder.encode(value, "utf-8");
			result = toHexString(encrypt(value, PASSWORD_CRYPT_KEY))
					.toUpperCase();
		} catch (Exception ex) {
			ex.printStackTrace();
			return "";
		}
		return result;
	}

	public static byte[] convertHexString(String ss) {
		byte digest[] = new byte[ss.length() / 2];
		for (int i = 0; i < digest.length; i++) {
			String byteString = ss.substring(2 * i, 2 * i + 2);
			int byteValue = Integer.parseInt(byteString, 16);
			digest[i] = (byte) byteValue;
		}
		return digest;
	}

	public static String toHexString(byte b[]) {
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			String plainText = Integer.toHexString(0xff & b[i]);
			if (plainText.length() < 2)
				plainText = "0" + plainText;
			hexString.append(plainText);
		}
		return hexString.toString();
	}
	//测试
	/*public static void main(String[] args) throws Exception {
	    DESCryption tools = new DESCryption(DESkey,DESIV);
	    System.out.println("加密:" + tools.encode("管理员"));
	    System.out.println("解密:" + tools.decode("T9YwLGYNbN0="));
	}*/
	}
